package com.jsh.ex.controller.oauth2;

import com.jsh.ex.exception.BaseException;
import com.jsh.ex.oauth2.OauthConnector;
import com.jsh.ex.oauth2.OauthUser;
import com.jsh.ex.oauth2.connector.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by wukai on 2017/9/18.
 */
@ApiIgnore
@Controller
@RequestMapping("/oauth2")
public class Oauth2Controller implements EnvironmentAware {
    private Map<String, OauthConnector> oauthConnectors = new HashMap<>();
    @Override
    public void setEnvironment(Environment environment) {
        RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment,"oauth.");
        Map<String,Object> subProperties = resolver.getSubProperties("");
        String type;String appKey;String appSecret;
        for(String key : subProperties.keySet()){
            type = key.split("\\.")[1];
            if(oauthConnectors.containsKey(type)) continue;
            appKey = environment.getProperty("oauth."+type+".appKey");
            appSecret = environment.getProperty(("oauth."+type+".appSecret"));
            if(QQConnector.SNS_TYPE.equals(type)){
                oauthConnectors.put(type,new QQConnector(appKey,appSecret));
            }else if(GithubConnector.SNS_TYPE.equals(type)){
                oauthConnectors.put(type, new GithubConnector(appKey, appSecret));
            }else if(OSChinaConnector.SNS_TYPE.equals(type)){
                oauthConnectors.put(type, new OSChinaConnector(appKey, appSecret));
            }else if(WechatConnector.SNS_TYPE.equals(type)){
                oauthConnectors.put(type, new WechatConnector(appKey, appSecret));
            }else if(WeiboConnector.SNS_TYPE.equals(type)){
                oauthConnectors.put(type, new WeiboConnector(appKey, appSecret));
            }
        }
    }
    @RequestMapping(value = "{type}", method = RequestMethod.GET)
    public String redirect(HttpServletRequest request, @PathVariable("type") String type){

        OauthConnector connector = oauthConnectors.get(type);
        if(connector == null)throw new BaseException("不支持授权类型:"+type);

        String state = UUID.randomUUID().toString().replaceAll("-", "");
        String callBackUrl = request.getRequestURL().toString().replace("/" + type, "/callback/" + type);
        String url = connector.getAuthorizeUrl(state, callBackUrl);

        request.getSession().setAttribute("oauth_state", state);
        return "redirect:" + url;
    }

    @RequestMapping(value = "callback/{type}", method = {RequestMethod.GET,RequestMethod.POST})
    public String callback(HttpServletRequest request, Model model, @PathVariable("type") String type) {
        String code = request.getParameter("code");
        String stateIn = request.getParameter("state");

        Object state = request.getSession().getAttribute("oauth_state");

        request.getSession().removeAttribute("oauth_state");
        if(state == null || !StringUtils.equalsIgnoreCase(stateIn, state.toString())){
            return "redirect:/index";
        }

        OauthConnector connector = oauthConnectors.get(type);

        OauthUser oauthUser = connector.getUser(code);
        //根据openid 找用户，
//        UserEntity userEntity = userService.findUserbyOpenIdAndType(type, oauthUser.getOpenId());
//
//        if(userEntity != null){
//            LoginUserInfo loginUserInfo = new LoginUserInfo(userEntity.getId(),userEntity.getNickname(),userEntity.getUserType());
//            loginUserInfo.setAvatar(userEntity.getAvatar());
//            request.getSession().setAttribute(Constants.LOGIN_SESSION_KEY, loginUserInfo);
//            return "redirect:/ucenter/index";
//        }
//
//        //跳转去绑定页面
//        model.addAttribute(PageMetaInfo.ATTR_NAME, PageMetaInfo.current().setModelName("user"));
//        model.addAttribute("oauthUser", oauthUser);
//        //
//        request.getSession().setAttribute("oauth_openid", type + ":" +state);
//
        return "user/bind";
    }
}
